package com.hiraeth.modules.monitor.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hiraeth.common.exception.RRException;
import com.hiraeth.common.utils.PageParams;
import com.hiraeth.modules.monitor.dao.MonitorDashboardDao;
import com.hiraeth.modules.monitor.entity.MonitorDashboard;
import com.hiraeth.modules.monitor.service.MonitorDashboardService;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class MonitorDashboardServiceImpl extends ServiceImpl<MonitorDashboardDao, MonitorDashboard> implements MonitorDashboardService {
    /**
     * 分页查询
     *
     * @param pageParams
     * @return
     */
    @Override
    public IPage<MonitorDashboard> findListPage(PageParams<MonitorDashboard> pageParams) {
        QueryWrapper queryWrapper = new QueryWrapper<MonitorDashboard>();
        return baseMapper.selectPage(pageParams, queryWrapper);
    }

    /**
     * 添加仪表盘
     *
     * @param dashboard
     * @return
     */
    @Override
    public MonitorDashboard addDashboard(MonitorDashboard dashboard) {

        int count = baseMapper.selectCount(new QueryWrapper<MonitorDashboard>().lambda().eq(MonitorDashboard::getDashboardName, dashboard.getDashboardName()));
        if (count > 0) {
            throw new RRException("同名仪表盘<" + dashboard.getDashboardName() + ">已存在!");
        }
        dashboard.setCreateTime(new Date());
        dashboard.setUpdateTime(dashboard.getCreateTime());
        baseMapper.insert(dashboard);
        return dashboard;
    }

    /**
     * 更新仪表盘
     *
     * @param dashboard
     * @return
     */
    @Override
    public MonitorDashboard updateDashboard(MonitorDashboard dashboard) {
        QueryWrapper<MonitorDashboard> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                    .eq(MonitorDashboard::getDashboardName, dashboard.getDashboardName())
                    .ne(MonitorDashboard::getDashboardId, dashboard.getDashboardId());
        MonitorDashboard saved = baseMapper.selectOne(queryWrapper);
        if (saved != null) {
            throw new RRException(String.format("%s同名仪表盘已存在!", dashboard.getDashboardName()));
        }
        dashboard.setUpdateTime(new Date());
        baseMapper.updateById(dashboard);
        return dashboard;
    }

    /**
     * 删除仪表盘
     *
     * @param dashboardId
     */
    @Override
    public void removeDashboard(Long dashboardId) {
        baseMapper.deleteById(dashboardId);
    }
}
